package introse;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.swing.JFileChooser;
import javax.swing.JTable;

public class tableToExcelExporter {

    public static void exportJTable(JTable table) {
        JFileChooser chooser = new JFileChooser();
        if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            try {
                tableToExcelExporter.exportJTable(table, chooser.getSelectedFile());
                positiveMessage posMsg = new positiveMessage(null, true);
                posMsg.setMessage("Excel file exported successfully");
                posMsg.setVisible(true);
            } catch (Exception ex) {
            }
        }
    }

    public static void exportJTable(JTable table, File newFile) throws Exception {
        StringBuilder content = new StringBuilder("");

        for (int i = 0; i < table.getModel().getColumnCount(); i++) {
            content.append(table.getColumnName(i) + "~@_@~");
        }

        content.append("\n\n");

        for (int i = 0; i < table.getModel().getRowCount(); i++) {
            for (int j = 0; j < table.getModel().getColumnCount(); j++) {
                int col = table.convertColumnIndexToView(j);
                String value = null;

                try {
                    value = (String) table.getModel().getValueAt(i, col);
                } catch (java.lang.ClassCastException e) {
                }

                if (value == null) {
                    value = "";
                }

                // CSV file
                content.append(value + "~@_@~");
            }
            content.append("\n");
        }

        writeToFile(content.toString().replaceAll(",", ".").replaceAll("~@_@~", ","), newFile);
    }

    private static void writeToFile(String data, File newFile) throws FileNotFoundException, UnsupportedEncodingException {
        File file = new File(newFile.getPath() + ".csv");
        PrintWriter writer = new PrintWriter(file, "UTF-8");

        writer.println(data);

        writer.close();
    }
}
